package uk.ac.lkl.takteen.energyapp;

import uk.ac.lkl.takteen.energyapp.data.EnergyAppDatabaseMetadata;
import uk.ac.lkl.takteen.energyapp.data.EnergyAppProvider;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class ReceivedChallengesList extends ListActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.itemslist);

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		Cursor cursor = managedQuery(getIntent().getData(),
				EnergyAppDatabaseMetadata.PROJECTION_RECEIVED_CHALLENGES, null,
				null, null);

		if (cursor != null) {
			// Used to map notes entries from the database to views
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
					R.layout.itemslist_item, cursor,
					new String[] { EnergyAppDatabaseMetadata.CHALLENGE_NAME },
					new int[] { R.id.item_name });
			setListAdapter(adapter);
		}

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Uri _uri = ContentUris.withAppendedId(
						EnergyAppProvider.RECEIVED_CHALLENGES_DIR, id);
				Log.w("cursor selected item id", _uri.getPath());

				Intent intent = new Intent(Intent.ACTION_VIEW, _uri,
						ReceivedChallengesList.this,
						ReceivedChallengeEditor.class);
				intent.setFlags((int) id);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onBackPressed() {
		Log.d("CDA", "onBackPressed Called");
		Intent intent = new Intent(Intent.ACTION_VIEW, null,
				ReceivedChallengesList.this, EnergyAppActivity.class);
		startActivity(intent);
	}
}
